// editor-plugins/table-row-bg-color.js
import { h } from 'vue';

// 表格行背景色插件
export function tableRowBgColorPlugin() {
  return {
    // 插件名称
    name: 'table-row-bg-color',
    
    // 初始化函数
    init(editor) {
      // 注册菜单
      editor.registerMenu({
        key: 'table-row-bg-color',
        factory() {
          return {
            // 菜单标题
            title: '行背景色',
            
            // 菜单图标
            iconSvg: '<svg viewBox="0 0 1024 1024" width="16" height="16"><path d="M880 112H144c-17.7 0-32 14.3-32 32v736c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V144c0-17.7-14.3-32-32-32z m-40 728H184V184h656v656z" fill="#1890ff"/><path d="M690.6 426.7L512 598.7 333.4 426.7c-4.7-4.7-12.3-4.7-17 0l-22.6 22.6c-4.7 4.7-4.7 12.3 0 17l200 200c4.7 4.7 12.3 4.7 17 0l200-200c4.7-4.7 4.7-12.3 0-17l-22.6-22.6c-4.7-4.6-12.3-4.6-17 0.1z" fill="#1890ff"/></svg>',
            
            // 菜单类型
            type: 'dropdown',
            
            // 下拉菜单内容
            dropdownMenu: {
              width: 200,
              height: 'auto',
              getContent: () => {
                // 创建颜色选择面板
                const container = document.createElement('div');
                container.className = 'w-e-table-row-bg-color-panel';
                
                // 预设颜色
                const colors = [
                  '', '#f2f2f2', '#ffe6e6', '#e6ffe6', '#e6f2ff', '#fff6cc',
                  '#ffcccc', '#ccffcc', '#cce6ff', '#ffffcc', '#ffcc99',
                  '#ff9999', '#99ff99', '#99ccff', '#ffff99', '#ffcc66'
                ];
                
                colors.forEach(color => {
                  const colorBtn = document.createElement('div');
                  colorBtn.className = 'w-e-color-btn';
                  colorBtn.style.backgroundColor = color || 'transparent';
                  colorBtn.style.border = '1px solid #ddd';
                  colorBtn.style.width = '24px';
                  colorBtn.style.height = '24px';
                  colorBtn.style.margin = '2px';
                  colorBtn.style.display = 'inline-block';
                  colorBtn.style.cursor = 'pointer';
                  
                  if (!color) {
                    colorBtn.innerHTML = '<svg viewBox="0 0 1024 1024" width="16" height="16"><path d="M880 112H144c-17.7 0-32 14.3-32 32v736c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V144c0-17.7-14.3-32-32-32z m-40 728H184V184h656v656z" fill="#ddd"/></svg>';
                    colorBtn.style.textAlign = 'center';
                  }
                  
                  colorBtn.addEventListener('click', () => {
                    setTableRowColor(editor, color);
                    // 关闭下拉菜单
                    const menuElem = container.closest('.w-e-dropdown-menu');
                    if (menuElem) {
                      menuElem.style.display = 'none';
                    }
                  });
                  
                  container.appendChild(colorBtn);
                });
                
                // 添加自定义颜色输入框
                const customColorContainer = document.createElement('div');
                customColorContainer.style.marginTop = '8px';
                customColorContainer.style.padding = '4px';
                
                const colorInput = document.createElement('input');
                colorInput.type = 'color';
                colorInput.className = 'w-e-color-input';
                colorInput.style.width = '100%';
                
                const applyBtn = document.createElement('button');
                applyBtn.className = 'w-e-btn';
                applyBtn.textContent = '应用';
                applyBtn.style.marginTop = '4px';
                applyBtn.style.width = '100%';
                
                applyBtn.addEventListener('click', () => {
                  const color = colorInput.value;
                  if (color) {
                    setTableRowColor(editor, color);
                    // 关闭下拉菜单
                    const menuElem = container.closest('.w-e-dropdown-menu');
                    if (menuElem) {
                      menuElem.style.display = 'none';
                    }
                  }
                });
                
                customColorContainer.appendChild(colorInput);
                customColorContainer.appendChild(applyBtn);
                container.appendChild(customColorContainer);
                
                return container;
              }
            }
          };
        }
      });
    }
  };
}

// 设置表格行背景色的函数
function setTableRowColor(editor, color) {
  const { selection } = editor;
  const selectedCells = selection.getTableSelectedCells();
  
  if (!selectedCells || selectedCells.length === 0) {
    editor.alert('请先选择表格中的行');
    return;
  }
  
  // 获取选中的行（去重）
  const rows = new Set();
  selectedCells.forEach(cell => {
    rows.add(cell.parentNode);
  });
  
  // 为每行设置背景色
  editor.cmd.do('insertHTML', ''); // 创建撤销点
  rows.forEach(row => {
    Array.from(row.children).forEach(cell => {
      const style = cell.getAttribute('style') || '';
      const newStyle = addOrUpdateStyle(style, 'background-color', color);
      cell.setAttribute('style', newStyle);
    });
  });
  
  editor.emit('change');
}

// 辅助函数：添加或更新样式属性
function addOrUpdateStyle(styleStr, key, value) {
  if (!styleStr) return `${key}:${value};`;
  
  const regex = new RegExp(`${key}\\s*:\\s*[^;]+;?`, 'gi');
  if (regex.test(styleStr)) {
    return styleStr.replace(regex, `${key}:${value};`);
  } else {
    return `${styleStr} ${key}:${value};`;
  }
}